package com.example.springsecuritydemo.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //表单提交
        http.formLogin()
                .loginPage("/login.html")//自定义登陆界面,必须放在static目录下，不能放在templates
                .loginProcessingUrl("/login")//当发现login时认为是登陆，必须和表单提交的地址一样，去执行MyUserDetailService
                .successForwardUrl("/tohome")//登陆成功后跳转页面，post请求
                .failureForwardUrl("/tohome")
                .and()
                //授权认证
                .authorizeRequests()
                .antMatchers("/login.html").permitAll()//login.html不需要认证
                .anyRequest().authenticated()//所有请求都必须别认证，必须登陆之后被访问
                .and()
                .csrf().disable();//关闭csrf
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                //
                .withUser("admin").password("$2a$10$9zFDlGQfQfOOX6oh.NH0UeHhq5p5iVAUf3wvZgUf6t9uLRwuMSiWW").roles("admin");
    }
}
